#include <memory>
#include <iostream>
#include <cstdio>
#include <sstream>
#include <algorithm>
#include "InstructionSrc.h"
#include "UserInterfaceException.h"

using namespace std;

std::shared_ptr<InstInput> InstructionSrc::GetInstruction(void)
{
    shared_ptr<InstInput> instIn(new InstInput);
    string strInput = GetInstructionFromSrc();
    StringTrim(strInput);
    if (strInput.empty()) {
        throw BlankInput();
    }
    ParseInstruction(strInput, instIn);
    return instIn;
}

void InstructionSrc::StringTrim(std::string &str)
{
    str.erase(str.begin(), std::find_if(str.begin(), str.end(),
              [](unsigned char ch) {return !std::isspace(ch); }));
    str.erase(std::find_if(str.rbegin(), str.rend(),
              [](unsigned char ch) {return !std::isspace(ch); }).base(), str.end());
}

void InstructionSrc::ParseInstruction(const std::string &strInput, std::shared_ptr<InstInput> &instIn)
{
    std::istringstream iss(strInput);
    iss >> instIn->instName;
    for (std::string token; iss >> token; ) {
        instIn->args.push_back(token);
    }
}